<?php
/** @noinspection PhpUnused */
declare(strict_types=1);

namespace app\shop\controller;

use app\shop\exception\FailException;
use app\shop\exception\ParamsErrorException;
use app\shop\logic\UserCartLogic;
use app\shop\validate\UserCartValidate;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * @property UserCartLogic $logic
 */
class UserCartController extends BaseController
{
    protected string $validateClassName = UserCartValidate::class;

    protected array $noNeedLogin = ['totalNum'];

    public function __construct(UserCartLogic $cartLogic)
    {
        parent::__construct();

        $this->logic = $cartLogic;
    }

    /**
     * 购物车列表
     * @return Json
     * @throws ParamsErrorException|DbException
     */
    public function index(): Json
    {
        $params = $this->getInput(true);

        $this->validateData($params, 'list');

        $result = $this->logic->list($params);

        return $this->success($result);
    }

    /**
     * 购物车添加
     * @return Json
     * @throws ParamsErrorException
     * @throws FailException
     */
    public function add(): Json
    {
        $params = $this->postInput(true);

        $this->validateData($params, 'add');

        $result = $this->logic->add($params);

        return $this->success($result);
    }

    /**
     * 购物车编辑
     * @return Json
     * @throws FailException
     * @throws ParamsErrorException
     */
    public function edit(): Json
    {
        $params = $this->postInput(true);

        $this->validateData($params, 'edit');

        $result = $this->logic->update($params);

        return $this->success($result);
    }

    /**
     * 购物车删除
     * @return Json
     * @throws FailException
     * @throws ParamsErrorException
     */
    public function delete(): Json
    {
        $params = $this->postInput(true);

        $this->validateData($params, 'delete');

        $this->logic->delete($params);

        return $this->success('删除成功');
    }

    /**
     * 购物车清空
     * @return Json
     * @throws DbException
     * @throws FailException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function clear(): Json
    {
        $params = $this->postInput(true);

        $this->logic->clear($params);

        return $this->success('清空成功');
    }

    /**
     * 购物车全选
     * @return Json
     */
    public function selectAll(): Json
    {
        $params = $this->postInput(true);

        $result = $this->logic->selectAll($params);

        return $this->success($result);
    }

    public function totalNum(): Json
    {
        $params = $this->getInput(true);

        if (empty($params['user_id'])) {
            $result = 0;
        } else {
            $result = $this->logic->getTotalNum($params);
        }

        return $this->success($result);
    }
}
